<?php


namespace app\common\lib;


use app\common\cachemodel\Recode;
use app\everyday\controller\IndexJob;
use think\Db;
use think\Log;
use think\queue\Job;

class FortuneDayJob
{
    /**
     * @param Job $job
     * @param $jobData
     */
    public function task(Job $job, $jobData)
    {
        Log::write('日运计算队列开始；执行数据：【' . json_encode($jobData, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . '】', 'log', true);
        if ($job->attempts() > 1)
        {
            Log::write('日运计算队列任务执行失败：【' . json_encode($jobData, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . '】：任务关闭', 'error', true);
            return $job->delete();
        }
        $t = time();
        $startDate = $jobData['start_date'];
        $endDate = $jobData['end_date'];
        try
        {
            $startTime = strtotime($startDate);
            $endTime = strtotime($endDate);
            $dayNum = ($endTime - $startTime) / 86400;
            $fortuneIndex = new IndexJob();
            $field = 'r.status,r.id,r.name,r.type,r.year,r.month,r.day,r.hour,r.minute,r.timezone,birth_country,birth_province,birth_city,live_country,live_province,live_city,comments,isself,long_deg,long_min,ew,lat_deg,lat_min,ns,avatar,is_summer,or_day,uid,aid,sun,moon,merc,venu,mars,jupi,satu,non,lili,juno,asc,mc,r.is_read';
            $data = (new Recode())->alias('r')
                ->join('app_recode_astro ra', 'r.aid=ra.id', 'LEFT')
                ->where(['r.isself' => 1])
                ->whereIn('uid', $jobData['uids'])
                ->column($field, 'r.id');

            foreach ($data as $recode)
            { // 备份档案信息
                $t1 = time();
                $backRecode = [
                    'uid' => $recode['uid'],
                    'create_time' => time(),
                    'recode' => json_encode($recode, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)
                ];
                print_r('用户id【' . $recode['uid'] . '】日运计算开始' . PHP_EOL);
                Log::write('用户id【' . $recode['uid'] . '】日运计算开始', 'log', true);
                // 备份档案 并取得ID
                $rbId = Db::table('wechat_backup_07_18_14_43_00.zl_fortune_day_recode_backup')->insertGetId($backRecode);
                print_r('用户id【' . $recode['uid'] . '】档案备份完成' . PHP_EOL);
                Log::write('用户id【' . $recode['uid'] . '】档案备份完成', 'log', true);
                $ym = date('Ym', $startTime);
                $insetSql = '';
                for ($d = 0; $d <= $dayNum; $d++)
                {
                    $time = $startTime + 86400 * $d;
                    if (date('Ym', $time) > $ym)
                    {// 如果开始计算下个月的数据 则先把上个月的数据写入数据库
                        $this->dataInsert($ym, $insetSql, (int)$recode['uid']);
                        $ym = date('Ym', $time);
                        $insetSql = ''; // 重置数据
                    }
                    $fortuneData = $fortuneIndex->init($time, $recode, 2);
                    $starLevel = 0;
                    foreach ($fortuneData['revive_day'] as $reviveDays)
                    {
                        if ($reviveDays['star_level'] > $starLevel)
                        {
                            $starLevel = $reviveDays['star_level'];
                        }
                        if ($starLevel > 2)
                        {
                            continue;
                        }
                    }
                    $content = json_encode($fortuneData, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
                    $date = (int)date('Ymd', $time);
                    $insetSql .= "({$fortuneData['sun_in_sign']},{$recode['uid']},{$date},{$starLevel},{$rbId},'{$content}'),";
                }
                if ($insetSql)
                {   // 写入数据
                    $this->dataInsert(date('Ym', $time), $insetSql, (int)$recode['uid']);
                }

                print_r('用户id【' . $recode['uid'] . '】日运计算结束，耗时' . (time() - $t1) . '秒' . PHP_EOL);
                Log::write('用户id【' . $recode['uid'] . '】日运计算结束，耗时' . (time() - $t1) . '秒', 'log', true);
            }
        }
        catch (\Exception $e)
        {
            print_r('【' . json_encode($jobData, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . '】日运计算错误：' . $e->getMessage() . PHP_EOL);
            Log::write('【' . json_encode($jobData, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . '】日运计算错误：' . $e->getMessage(), 'error', true);
            return $job->delete();
        }

        Log::write('日运计算队列结束；总耗时(' . (time() - $t) . ')秒，执行数据：【' . json_encode($jobData, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . '】', 'log', true);
        $job->delete();
    }

    public function dataInsert(string $ym, string $dataStr, int $uid)
    {
        $sta = '写入';
        $num = Db::table('wechat_backup_07_18_14_43_00.zl_fortune_day_' . $ym . '00')->where('uid', $uid)->count();
        if ($num)
        {
            Db::table('wechat_backup_07_18_14_43_00.zl_fortune_day_' . $ym . '00')->where('uid', $uid)->delete();
            $sta = '更新';
        }
        $insetSql = 'INSERT INTO `wechat_backup_07_18_14_43_00`.`zl_fortune_day_' . $ym . '00`(`sun_in_sign`,`uid`,`date`,`star_level`,`rbid`,`content`)  VALUES' . $dataStr;
        $insetSql = rtrim($insetSql, ',');
        Db::execute($insetSql);
        print_r("用户id【{$uid}】{$ym}日运{$sta}完成" . PHP_EOL);
        Log::write("用户id【{$uid}】{$ym}日运{$sta}完成", 'log', true);
    }
}
